package com.topvision.jack.uploadlibrary.presenter;

import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.util.Log;

import com.topvision.jack.uploadlibrary.entity.UploadFileEntity;
import com.topvision.jack.uploadlibrary.model.IUploadModel;
import com.topvision.jack.uploadlibrary.model.UploadModelImpl;
import com.topvision.jack.uploadlibrary.receiver.UploadReceiver;
import com.topvision.jack.uploadlibrary.task.UploadManager;
import com.topvision.jack.uploadlibrary.task.UploadTask;
import com.topvision.jack.uploadlibrary.task.UploadTaskListener;
import com.topvision.jack.uploadlibrary.utils.BlueToothUtil;
import com.topvision.jack.uploadlibrary.utils.FileUtils;
import com.topvision.jack.uploadlibrary.utils.OkHttpRequestUtils;
import com.topvision.jack.uploadlibrary.utils.UploadUtils;
import com.topvision.jack.uploadlibrary.view.UploadView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by gushenjie on 17/12/24.
 */

public class UploadPresenterImpl implements IUploadPresenter {
    //1M
    public final int DEFAULT_BLOCK_LENGTH = 1 * 1024 * 1024;
    Context context;
    UploadView uploadView;
    IUploadModel uploadModel;
    UploadReceiver uploadReceiver;

    public UploadPresenterImpl(Context context) {
        this.context = context;
        // this.uploadView = uploadView;
        uploadModel = new UploadModelImpl(context);

    }


    @Override
    public void upload(final String baseApiUrl, final UploadFileEntity uploadFileEntityVo, final UploadTaskListener uploadTaskListener) {
        if (uploadFileEntityVo.getBlockLength() == 0) {
            uploadFileEntityVo.setBlockLength(DEFAULT_BLOCK_LENGTH);
        }
        final String fileName = FileUtils.getFileName(uploadFileEntityVo.getFilePath());
        //用于筛选条件
        Map<String,String> params = uploadFileEntityVo.getData();
        if(params == null){
            params = new HashMap<>();
        }
        params.put("fileName", fileName);
        params.put("guid", BlueToothUtil.getBtMacNoColons(context));

        UploadFileEntity uploadFileEntity = uploadModel.queryUploadEntity(fileName);
        //查询是否已存在
        if (uploadFileEntity == null) {
            //保存到本地数据中
            UploadFileEntity uploadFileEntityDb = new UploadFileEntity(fileName, uploadFileEntityVo.getFilePath(), uploadFileEntityVo.getBlockLength());
            uploadModel.addUploadFileEntity(uploadFileEntityDb);
        }
        //首先获取chuck
        OkHttpRequestUtils.getInstance(context).OkHttpGetStringRequest(baseApiUrl + "ckeckFileServlet", params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                Log.e("tvLog", e.getMessage());
            }

            @Override
            public void onResponse(String response) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt("code");
                    if (code == 0) {
                        final int chunk = Integer.valueOf(jsonObject.get("data").toString());
                        UploadTask task = new UploadTask.Builder().setContext(context)
                                .setApiUrl(baseApiUrl)
                                .setId(fileName)
                                .setUrl(uploadFileEntityVo.getFilePath())
                                .setChunck(chunk)
                                .setFileName(fileName)
                                .setUploadFileEntity(uploadFileEntityVo)
                                .setBlockLength(uploadFileEntityVo.getBlockLength())
                                .setUploadModel(uploadModel)
                                .setListener(uploadTaskListener).build();
                        UploadManager.getInstance().addUploadTask(task);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void uploadTasks(String baseApiUrl, UploadTaskListener uploadTaskListener) {
        List<UploadFileEntity> list = uploadModel.loadAll();
        for (UploadFileEntity uploadEntity : list) {
            upload(baseApiUrl, uploadEntity, uploadTaskListener);
        }
    }

    @Override
    public void pauseTasks() {
        Map<String, UploadTask> map = UploadManager.getInstance().getUploadTasks();
        for (Map.Entry<String, UploadTask> entry : map.entrySet()) {
            UploadManager.getInstance().pause(entry.getKey());
        }
    }

    @Override
    public void registerNetWorkListener(String baseApi, UploadTaskListener uploadTaskListener) {
        if (uploadReceiver == null) {
            uploadReceiver = new UploadReceiver(baseApi, uploadTaskListener);
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(UploadUtils.ACTION_NETWORK);
        intentFilter.addAction(UploadUtils.ACTION_NETWORK_FAILED);
        context.registerReceiver(uploadReceiver, intentFilter);
    }

    @Override
    public void unRegisterNetWorkListener() {
        if (uploadReceiver != null) {
            context.unregisterReceiver(uploadReceiver);
        }
    }
}
